﻿using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Timers;
using System.Windows;
using MyUtils;

namespace FitAutomation.WPF
{
	class MainWindowViewModel : ObservableObject
	{
		public MainWindowViewModel()
		{
			_timer = new Timer(5000);
			_timer.Elapsed += TimerElapsed;
			_timer.Start();
		}

		void TimerElapsed(object sender, ElapsedEventArgs e)
		{
			OnPropertyChanged("HostProcess");
			_processes.Value.Update();
		}

		readonly Timer _timer;

		public string HostProcess
		{
			get
			{
				var pid = FitAutomationFacade.HostProcessId;
				var process = Process.GetProcessById(pid);
				return ProcessPresenter(process);
			}
		}

		public string ThisProcess
		{
			get
			{
				var process = Process.GetCurrentProcess();
				return ProcessPresenter(process);
			}
		}

		static string ProcessPresenter(Process process)
		{
			return process.Id + ": " + process.ProcessName + ": " + process.MainModule.FileName;
		}

		readonly Lazy<SmartUpdateCollection<ProcessIdentifier>> _processes = Lazy.New(() =>
			{
				var col = new SmartUpdateCollection<ProcessIdentifier>(
					Enumerable.Empty<ProcessIdentifier>
					// FitAutomationFacade.GetRegisteredProcesses
					); 
				col.CollectionChanged += ProcessesCollectionChanged;
				return col;
			} );

		static void ProcessesCollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			Debug.WriteLine(e.Action + ": " + e.OldStartingIndex + " " + e.NewStartingIndex);
		}

		public SmartUpdateCollection<ProcessIdentifier> Processes
		{
			get { return _processes.Value; }
		}
	}
}
